import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../model/main_view_model.dart';
import '../../../app_files.dart';

Effect<CommunityListViewState> buildEffect() {
  return combineEffects(<Object, Effect<CommunityListViewState>>{
    CommunityListViewAction.action: _onAction,
    Lifecycle.initState: _initState,
    CommunityListViewAction.onLoad: _onLoad,
    CommunityListViewAction.onTapSort: _onTapSort,
  });
}

void _onAction(Action action, Context<CommunityListViewState> ctx) {}

void _initState(Action action, Context<CommunityListViewState> ctx) {
  _sendRequest(ctx, 1);
}

void _onLoad(Action action, Context<CommunityListViewState> ctx) async {
  await _sendRequest(ctx, action.payload);
}

void _onTapSort(Action action, Context<CommunityListViewState> ctx) async {
  ctx.state.sortIndex = action.payload;
  ctx.dispatch(CommunityListViewActionCreator.setSort(action.payload));
  _sendRequest(ctx, 1);
}

_sendRequest(Context<CommunityListViewState> ctx, int page) async {
  if (ctx.state.type == 1) {
    ResultData res = await CommonNetWork.patrolAreaList(
      status: ctx.state.sortIndex,
      userID: ctx.state.userID,
      page: page,
      pageSize: 10,
    );
    if (res.success) {
      List list = res.data['data'];
      List items = list.map((e) => PatrolAreaModel.fromJson(e)).toList();
      ctx.dispatch(CommunityListViewActionCreator.onGetData(items, page));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
      ctx.dispatch(CommunityListViewActionCreator.onGetData([], page));
    }
    return;
  }
  ResultData res = await CommonNetWork.communityList(
      status: ctx.state.sortIndex, userID: ctx.state.userID);
  if (res.success) {
    List list = res.data['data'];
    List items = list.map((e) => CommunityItemModel.fromJson(e)).toList();
    ctx.dispatch(CommunityListViewActionCreator.onGetData(items, page));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
    ctx.dispatch(CommunityListViewActionCreator.onGetData([], page));
  }
}
